package com.study.es.test;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.IOException;

/**
 * @author MI
 * @version 1.0
 * @date 2021/4/24 21:49
 */
public class ESTest_Doc_Query {
    public static void main(String[] args) throws IOException {
        // 创建ES客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );

        final SearchRequest request = new SearchRequest();
        request.indices("user");

        //查询全部数据
        final SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());

        request.source(query);


        final SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);
        final SearchHits hits = response.getHits();
        System.out.println(hits.getTotalHits());

        for (SearchHit hit : hits) {
            System.out.println(hit);
        }
        // 关闭ES客户端
        esClient.close();
    }
}
